package com.jin.webvideo.externalInterfaces;

import com.jin.webvideo.util.sys.ClientUtil;
import org.springframework.core.io.ClassPathResource;

import javax.script.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JSUtil {
    private static ScriptEngine jsEngine;
    private static Map<String, Bindings> bindings;
    static {
        bindings = new HashMap<>();
        ScriptEngineManager manager = new ScriptEngineManager();
        jsEngine = manager.getEngineByName("js");
    }
    public static Bindings binding(String name){
        Bindings binding = bindings.get(name);
        if (null == binding){
            binding = jsEngine.createBindings();
            bindings.put(name, binding);
            loadLocalJSFile("inject.js", name);
        }
        return binding;
    }
    public static Object loadLocalJSFile(String fileName, String name) {
        Object obj = null;
        ClassPathResource resource = new ClassPathResource("res/"+fileName);
        InputStream input = null;
        try {
            input = resource.getInputStream();
            String js = ClientUtil.toString(input);
            obj = eval(js, name);
        } catch (IOException | ScriptException e) {
            e.printStackTrace();
        }
        finally {
            if (null != input){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }
    public static Object evalEx(String script, String name){
        Object result = null;
        try {
            result = eval(script, name);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static Object eval(String script, String name) throws ScriptException {
        Bindings bindings = binding(name);
        return jsEngine.eval(script, bindings);
    }
}
